<?php
// +----------------------------------------------------------------------
// | 中联致远服务端框架
// +----------------------------------------------------------------------
// | Copyright (c) 2018 http://www.zhongliansoft.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: tony <tanyu@zhongliansoft.com>
// +----------------------------------------------------------------------

namespace app\common\model;
use think\Validate;
use app\common\model\ViewGetStudentList as ViewGetStudentListModel;
use app\common\model\BookDraw as BookDrawModel;
use app\common\model\BookReturn as BookReturnModel;
use app\common\model\BookAccount as BookAccountModel;
use app\common\model\Config as ConfigModel;
use think\model\concern\SoftDelete;
use think\facade\Log;

class BookAdjust extends Common
{
    //时间自动存储
    protected $autoWriteTimestamp = true;
    protected $updateTime = 'date';

    protected $rule = [
        'remark'          => 'require|max:50',
    ];
    protected $msg = [
        'remark.require'  => '请输入调整原因',
        'remark.max'      => '调整原因长度最大50位',
    ];

    /**
     * 设置csv header
     * @return array
     */
    public function csvHeader()
    {
        return [
            [
                'id'   => 'plan_year',
                'desc' => '年度',
            ],
            [
                'id'   => 'plan_season',
                'desc' => '季度',
            ], 
            [
                'id'   => 'xh',
                'desc' => '学生学号',
            ],
            [
                'id'   => 'xm',
                'desc' => '学生姓名',
            ],
            [
                'id'   => 'type',
                'desc' => '类型',
            ],
            [
                'id'   => 'book_name',
                'desc' => '教材名称',
            ],
            [
                'id'   => 'book_isbn',
                'desc' => 'ISBN书号',
            ],
            [
                'id'   => 'remark',
                'desc' => '调整原因',
            ]
        ];
    }

    /**
     * @param $post
     *
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function tableData($post)
    {
        if(isset($post['limit'])){
            $limit = $post['limit'];
        }else{
            $limit = config('paginate.list_rows');
        }
       
        $tableWhere = $this->tableWhere($post);
        $list = $this->alias('a')
                        ->field("a.id, a.year, case when a.season = 1 then '春季' when a.season = 3 then '秋季' end season, c.bmmc, d.zymc, e.bjmc, b.xh, b.xm, g.book_name, g.book_author, g.book_concern, g.book_edition, g.book_isbn, a.book_num, a.book_price, a.book_disc, FROM_UNIXTIME(a.date) date, a.remark, f.username")
                        ->leftjoin('zl_student_info b', 'a.xh = b.xh')
                        ->leftjoin('zlzhsf.pbmdm c', 'a.bmdm = c.bmdm')
                        ->leftjoin('zlzhsf.pzydm d', 'a.zydm = d.zydm')
                        ->leftjoin('zlzhsf.pbjdm e', 'a.bjdm = e.bjdm')
                        ->leftjoin('zl_manage f', 'a.operid = f.id')
                        ->leftjoin('zl_book_info g', 'a.book_id = g.id')
                        ->where($tableWhere['where'])->order($tableWhere['order'])->paginate($limit);
        $data = $this->tableFormat($list->getCollection());         //返回的数据格式化，并渲染成table所需要的最终的显示数据类型

        $re['code'] = 0;
        $re['msg'] = '';
        $re['count'] = $list->total();
        $re['data'] = $data;
        return $re;
    }
  
    //where搜索条件
    protected function tableWhere($post)
    {
        $where = [];
        if(isset($post['year']) && $post['year'] != ""){
            $where[] = ['a.year', '=', $post['year']];
        }
        if(isset($post['season']) && $post['season'] != ""){
            $where[] = ['a.season', '=', $post['season']];
        }
        if(isset($post['dep_id']) && $post['dep_id'] != ""){
            $where[] = ['a.bmdm', '=', $post['dep_id']];
        }
        if(isset($post['specialty_id']) && $post['specialty_id'] != ""){
            $where[] = ['a.zydm', '=', $post['specialty_id']];
        }
        if(isset($post['class_id']) && $post['class_id'] != ""){
            $where[] = ['a.bjdm', '=', $post['class_id']];
        }
        if(isset($post['xh']) && $post['xh'] != ""){
            $where[] = ['b.xh', '=', $post['xh']];
        }
        if(isset($post['xm']) && $post['xm'] != ""){
            $where[] = ['b.xm', 'like', '%'.$post['xm'].'%'];
        }
        if(isset($post['id']) && $post['id'] != ""){
            $where[] = ['a.id', 'eq', $post['id']];
        }
        
        $result['where'] = $where;
        $result['field'] = "*";
        $result['order'] = ['a.id ASC'];
        return $result;
    }

    /**
     * @param $list
     *
     * @return mixed
     */
    protected function tableFormat($list)
    {
        // foreach($list as &$val){
        //     $val['date'] = getTime($val['date']);
        // }
        return $list;
    }

    /**
     * 调整
     * @param $data
     * @return array
     */
    public function bookAdjust($data)
    {
        $return = [
            'status' => false,
            'msg'    => '调整失败',
            'data'   => ''
        ];

        $books = $data['books'];
        $remark = $data['remark'];
        $operid = session('manage')['id'];
        $list       = explode(",", $books);
 
        //校验数据
        $validate = new Validate($this->rule, $this->msg);
        if (!$validate->check($data)) {
            $return['msg'] = $validate->getError();
            return $return;
        } 

        $update_xh = '';
        foreach($list as $val) {
            $valList  = explode(";", $val);

            $type = $valList[0];
            $xh = $valList[1];
            $update_xh = $xh;
            $isbn = $valList[2];

            $model = new Common();
            $model->query("call bookAdjust('".$type."','".$xh."','".$isbn."','".$remark."','".$operid."');");
        }

        // 设置账表状态
        // $config = new ConfigModel();
        // $year = $config->getYear();
        // $season = $config->getSeason();
        // $bookAccountModel = new BookAccountModel();
        // $bookAccountModel->save(['status'=>0], ['year'=>$year, 'season'=>$season, 'xh'=>$update_xh]);
        
        $return['data']   = [];
        $return['status'] = true;
        $return['msg']    = '调整成功'; 
        \think\facade\Request::token('__ZlServer_Token__', 'sha1');
        return $return;
    }
}